package cn.timelost.qy.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.timelost.qy.config.UploadConfig;
import cn.timelost.qy.service.UploadService;
import cn.timelost.qy.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class UploadServiceImpl implements UploadService {

    @Resource
    private UploadConfig uploadConfig;

    @Override
    public Long uploadFile(MultipartFile file) {
        return upload(file);
    }

    private Long upload(MultipartFile file) {
        Long id = IdUtil.getSnowflakeNextId();
        String path = createPath(file, id);

        String originName = file.getOriginalFilename();
        try {
            FileUtil.writeBytes(file.getBytes(), path);
            log.info("上传文件：" + originName + "。时间：" + DateUtil.now());
            return id;
        } catch (IOException e) {
            log.info("上传文件失败：" + originName + "。时间：" + DateUtil.now());
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * 创建文件存储路径
     */
    private String createPath(MultipartFile file, Long id) {
        return uploadConfig.path + id + "." + FileUtil.getSuffix(file.getOriginalFilename());
    }

    @Override
    public boolean delFileFromDisk(List<String> snowFileNames) {
        for (String snowFileName : snowFileNames) {
            if (!FileUtil.del(createPath(snowFileName))) {
                throw new RuntimeException("文件删除失败！" + snowFileName);
            }
        }
        return true;
    }

    /**
     * 创建文件存储路径
     */
    private String createPath(String snowFileName) {
        return uploadConfig.path + snowFileName;
    }

    @Override
    public String getIpv4() {
        return IpUtil.getAddress() + ":" + uploadConfig.port;
    }

}
